// 代码块 importM
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, // 去掉debugger图标
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

// 父widget
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.refresh),
            onPressed: () {
              setState(() {
                // 获取子widget属性
                var boxState = _globalKey.currentState as _BoxState;
                print(boxState._count);
                setState(() {
                  boxState._count++;
                });
                // 调用 子widget 方法
                boxState.run();

                // 2 获取子widget (了解)
                var boxWidget = _globalKey.currentWidget as Box;
                print(boxWidget.color); //  MaterialColor(primary value: Color(0xfff44336))

                // 3 获取子widget 渲染熟悉 (了解)
                var renderBox = _globalKey.currentContext!.findRenderObject() as RenderBox;
                print(renderBox.size); // Size(100.0, 100.0)
              });
            }),
        appBar: AppBar(
          title: const Text("Title"),
        ),
        body: Center(child: Box(key: _globalKey, color: Colors.red)));
  }
}

// 子widget
class Box extends StatefulWidget {
  final Color color;
  const Box({super.key, required this.color});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _count = 0;
  void run() {
    print("我是box的run方法");
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 100,
      height: 100,
      child: ElevatedButton(
          style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(widget.color)),
          onPressed: () {
            setState(() {
              _count++;
            });
          },
          child: Text(
            "$_count",
            style: Theme.of(context).textTheme.displayLarge,
          )),
    );
  }
}
